import './prefix.css'
import './app.css'
import './index.scss'

import {beautifyHtml, makeid} from './utils'
import isObject from 'lodash/isObject'

import './vma/core'
import './pageapp/core'

import './xy-ui'
import './litelements'

import { getDomSel } from './dom'
import { getComDef } from './com'

let curDom
let TreeDomId = 'treeDemo'
let buttonDisabledClass = 'domBtn_Disabled'
let buttonDefaultClass = 'domBtnDrag'
let domBtnDivClass = 'domBtnDiv'

let MoveTest = {
  curTarget: null,
  curTmpTarget: null,
  noSel: function () {
    try {
      window.getSelection
        ? window.getSelection().removeAllRanges()
        : document.selection.empty()
    } catch (e) {}
  },
  dragTree2Dom: function (treeId, treeNodes) {
    return !treeNodes[0].isParent
  },
  prevTree: function (treeId, treeNodes, targetNode) {
    return (
      !targetNode.isParent && targetNode.parentTId === treeNodes[0].parentTId
    )
  },
  nextTree: function (treeId, treeNodes, targetNode) {
    return (
      !targetNode.isParent && targetNode.parentTId === treeNodes[0].parentTId
    )
  },
  innerTree: function (treeId, treeNodes, targetNode) {
    return (
      targetNode != null &&
      targetNode.isParent &&
      targetNode.tId === treeNodes[0].parentTId
    )
  },
  clear: function() {
    var zTree = MoveTest.getZtree()
    var nodes = zTree.getNodes();
    if (nodes && nodes.length>0) {
      zTree.removeNode(nodes[0]);
    }
  },
  addBlockNode: function(index) {
    var target = document.getElementById('dom_3').children[index].cloneNode()
    MoveTest.dom2TreeCore($(target),  null)
  },
  dom2TreeCore: function(target, treeNode) {
    // console.log('dom2TreeCore')
    let targetDataset = target.data()
    // console.log(targetDataset)
    var parentNode
    if (treeNode != null && treeNode.isParent) {
      parentNode = treeNode
    } else if (treeNode != null && !treeNode.isParent) {
      parentNode = treeNode.getParentNode()
    }
    // console.log(target)

    if (targetDataset.blockNodes) {
      let init = () => {
        window.vvg.blocks[targetDataset.blockNodes](MoveTest.addNodes, {
          parentNode,
        }).reload().then(res => {
          let {js, html, css} = res
          //  transformJsx
          let key = '__tmpNodes'
          globalThis.transformJsx(
            `/** @jsx vvg.el*/ window.__tmpNodes = (${html})`,
            function (v) {
              if (v) {
                eval(v);
                window.vvg.page.css = css
                window.vvg.pageEditors.update('style', css)
                window.vvg.page.js = js
                window.vvg.pageEditors.update('js', js)
                for (let extKey in window.vvg.page.ext) {
                  window.vvg.updateEventListen(extKey)
                }

                let pageapp = getVma('pageapp')
                for (let key in vvg.page.ext) {
                  pageapp.$refs.com.initExt(key, vvg.page.ext[key].trim())
                }

                window.MoveTest.getZtree().addNodes(null, window[key])
              }
            }
          )
          //  transformJsx
        })
      }

      vvg.blocks.reload = function() {
        MoveTest.clear()
        init()
      }

      init()
    } else {
      let dataset = target.data()
      if (!!parentNode) {
        // let parentNodeDataset = getDataset(parentNode.domId)
        if (dataset.canChild) {
          MoveTest.addFolder(parentNode, target)
        } else {
          MoveTest.addNodesV1(parentNode, target)
        }
      } else {
        target.removeClass(buttonDisabledClass)
        target.addClass(buttonDefaultClass)
        if (dataset.canChild) {
          MoveTest.addFolder(null, target)
        }
      }
      if (dataset.runId) {
        if (window.vvg.elements[dataset.runId] && window.vvg.elements[dataset.runId].run) {
          window.vvg.elements[dataset.runId].run()
        }
      }
      // window.MoveTest.updateType()
      if (window.vvg.onDom2treeUpdate) {
        window.vvg.onDom2treeUpdate()
      }
    }

  },
  dom2Tree: function (e, treeId, treeNode) {
    console.log(treeNode)
    var target = MoveTest.curTarget,
      tmpTarget = MoveTest.curTmpTarget
    if (!target) return


    MoveTest.dom2TreeCore(target, treeNode)

    if (tmpTarget) tmpTarget.remove()

    MoveTest.curTarget = null
    MoveTest.curTmpTarget = null
  },
  addNodes(parentNode, opt, ext) {
    var zTree = MoveTest.getZtree()
    let id =  Date.now()
    return zTree.addNodes(parentNode, {
      id,
      // domId: 'ele_',
      name: opt['name'],
      isParent: opt.isParent,
      open: true,
      attributes: {
        ['sid']: id
      },
      ...ext,
    })
  },
  addFolder(parentNode, target) {
    return MoveTest.addNodesV1(parentNode, target, {
      isParent: true
    })
  },
  addNodesV1(parentNode, target, opt = {}) {
    return MoveTest.addNodes(parentNode,  {
      domId: target.attr('domId'),
      name: target.text(),
      ...opt
    }, {
      dataset: target.data()
    })
  },
  updateType: function () {
    vvg.toggleLoading(true)

    var zTree = MoveTest.getZtree(),
      nodes = zTree.getNodes()
    // console.log(zTree.transformToArray(nodes))

    let dom = document.createElement('div')

    // // 遍历单个节点
    function traverseNode(node, isRoot) {
      if (!isRoot) {

        // if (window.vvg.page.des[node.dataset.comType]) {
        //   let des = window.vvg.page.des[node.dataset.comType]
        //   for (let key in des) {
        //     let desStyleObj = parseStyleToObj(des[key].value)
        //     console.log('jet', key, des[key], desStyleObj)
        //     sstyle(node, des[key], desStyleObj)
        //   }
        // }

        if (node.isParent && !node.pId) {
          var def = getComDef('ParentCom', node)
          var el = def.getEl()
          dom.appendChild(el)
        } else {
          var par = dom.querySelector(getDomSel(node.pId))
          if (par) {
            var def = getComDef('SubCom', node)
            var el = def.getEl()
            par.appendChild(el)
          }
        }
      }
      // console.log(dom.innerHTML)
    }

    function traverseTree(node, isRoot) {
      if (!node) {
        return
      }

      traverseNode(node, isRoot)
      if (node.children && node.children.length > 0) {
        var i = 0
        for (i = 0; i < node.children.length; i++) {
          traverseTree(node.children[i], false)
        }
      }
    }

    traverseTree(
      {
        children: nodes,
      },
      true
    )

    setTimeout(() => {
      console.log('renderIframe', window.vvg.page.ext)
      window.renderIframe(function (html, cb) {
        if (window.ART) {
          let ext = {}
          if (window.vvg.page.ext) {
            for (let key in window.vvg.page.ext) {
              ext[key] = window.vvg.page.ext[key]
            }
          }
          window.getVma('pageapp').$refs.com.renderAceEditor('code',
            function () {
              return ''
            }
            , {
              onEnd(parsedHtml) {
              }
            })

          // console.log('html', html)
          globalThis.transformJs(window.vvg.page.js, function (js) {
            globalThis.transformStyle(window.vvg.page.css, function (css) {
              if (!html) {
                cb(html)
                return
              }
              let _domhtml =  window.ART.render(
                `
{{each blocks}}{{@ $value}}{{/each}}
  <div id="app" >${dom.innerHTML}</div>
                    `.trim()
                ,{
                  blocks: ext,
                }
              )
              let h =  window.ART.render(
                html,
                {
                  ...ext,
                  blocks: ext,
                  content:  _domhtml,
                  csscontent: css,
                  beforeheader:'',
                  script: js,
                  afterheader: '',
                },
                {}
              )

              window.getVma('pageapp').$refs.com.renderAceEditor('code',
                function () {
                // console.log('dom.innerHTML', dom.innerHTML)
                  return beautifyHtml(dom.innerHTML)
                }
                , {
                  onEnd(parsedHtml) {
                    window.vvg.page.html = parsedHtml
                  }
                })

              cb(h)
            })
          })
        } else {
          cb(html)
        }
      })
    }, 0)
  },
  onRemove: function () {
    MoveTest.updateType()
  },
  bindDom: function () {
    // console.log('.' + domBtnDivClass)
    $('.' + domBtnDivClass).bind('mousedown', MoveTest.bindMouseDown)
  },
  bindMouseDown: function (e) {
    var target = e.target
    if (target != null && target.className === buttonDefaultClass) {
      var doc = $(document),
        target = $(target),
        docScrollTop = doc.scrollTop(),
        docScrollLeft = doc.scrollLeft()
      // target.addClass(buttonDisabledClass);
      // target.removeClass(buttonDefaultClass);
      curDom = $(
        `<span class='dom-tmp ${buttonDefaultClass}'>${target.text()}</span>`
      )
      curDom.appendTo('body')

      curDom.css({
        top: e.clientY + docScrollTop + 3 + 'px',
        left: e.clientX + docScrollLeft + 3 + 'px',
      })
      MoveTest.curTarget = target
      MoveTest.curTmpTarget = curDom

      doc.bind('mousemove', MoveTest.bindMouseMove)
      doc.bind('mouseup', MoveTest.bindMouseUp)
      doc.bind('selectstart', MoveTest.docSelect)
    }
    if (e.preventDefault) {
      e.preventDefault()
    }
  },
  bindMouseMove: function (e) {
    MoveTest.noSel()
    var doc = $(document),
      docScrollTop = doc.scrollTop(),
      docScrollLeft = doc.scrollLeft(),
      tmpTarget = MoveTest.curTmpTarget
    if (tmpTarget) {
      tmpTarget.css({
        top: e.clientY + docScrollTop + 3 + 'px',
        left: e.clientX + docScrollLeft + 3 + 'px',
      })
    }
    return false
  },
  bindMouseUp: function (e) {
    var doc = $(document)
    doc.unbind('mousemove', MoveTest.bindMouseMove)
    doc.unbind('mouseup', MoveTest.bindMouseUp)
    doc.unbind('selectstart', MoveTest.docSelect)

    var target = MoveTest.curTarget,
      tmpTarget = MoveTest.curTmpTarget
    if (tmpTarget) tmpTarget.remove()

    var jqEle = $(e.target).parents('#' + TreeDomId)
    if (jqEle.length === 0) {
      if (target) {
        target.removeClass(buttonDisabledClass)
        target.addClass(buttonDefaultClass)
      }
      MoveTest.curTarget = null
      MoveTest.curTmpTarget = null
    }
  },
  bindSelect: function () {
    return false
  },
  getZtree() {
    return $.fn.zTree.getZTreeObj('' + TreeDomId)
  },
}

import { addDiyDom } from './ztree'
import {objToStyle, parseStyleToObj, sstyle} from "./pageapp/utils";
var setting = {
  edit: {
    enable: true,
    showRemoveBtn: true,
    showRenameBtn: false,
    drag: {
      isCopy: false,
      isMove: false,
    },
  },
  data: {
    keep: {
      parent: true,
      leaf: true,
    },
    simpleData: {
      enable: true,
    },
  },
  callback: {
    onMouseUp: MoveTest.dom2Tree,
    onRemove: MoveTest.onRemove,
    onClick: function (e, treeId, treeNode, clickFlag) {
      if (clickFlag === 1) {
        document.dispatchEvent(
          new CustomEvent('com:selected', {
            detail: {
              treeNode,
            },
          })
        )
      }
    },
  },
  view: {
    selectedMulti: false,
    addDiyDom
  },
}

$(document).ready(function () {
  let defSetting = {
    isParent: true,
    open: true,
  }
  window.vvg.el = function (name, attrs, ...children) {
    let id = makeid(10)
    if (attrs && attrs.id) {
      id = attrs.id
    }
    if (!attrs) {
      attrs = {
      }
    }
    attrs['sid'] = id
    for (let attrKey in attrs) {
      if (attrs[attrKey] && attrs[attrKey].trim) {
        attrs[attrKey] = attrs[attrKey].trim()
      }
    }
    let ret = {
      name,
      id,
      attributes: attrs,
      ...{
        dataset: {
          comType: name,
        },
      },
      ...defSetting,
      children: []
    }
    children.forEach(function(childrenItem) {
      if (isObject(childrenItem) && childrenItem.id) {
        ret.children.push(childrenItem)
      } else {
        ret.textContent = children[0]
      }
    })
    return ret
  }

  if (window.vvg.init) {
    window.vvg.init()
  }

  let zNodes = window.vvg.zNodes ? window.vvg.zNodes : []
  zNodes = []
  $.fn.zTree.init($('#' + TreeDomId), setting, zNodes)
  MoveTest.bindDom()
  if (window.vvg.ready) {
    window.vvg.ready()
  }
})

window.renderIframe = function (
  render = function (v, cb) {
    cb(v)
  }
) {
  render(window.vvg.tpl, function (_html) {
    let webview = document.getElementById('testWebview')
    if ( webview ) {
      webview.useragent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
      // webview.src = `data:text/html;charset=utf-8,${encodeURIComponent(_html)}`
      axios.put('/api/tmpfile', {
        html: _html
      }).then(() => {
        // console.log(_html)
        webview.src = '/tmp?now=' + Date.now()
        // webview.addEventListener('dom-ready', () => {
        //   // webview.openDevTools()
        //   window.vvg.toggleLoading(false)
        // })
        window.vvg.toggleLoading(false)
        window.vvg.reloadSubWebview()
      })
    }
  })
}

window.vvg.reloadSubWebview = function () {
  setTimeout(() => {
    globalThis.electron.ipcRenderer.send('reloadchildurl')
  }, 1000)
}

// 事件监听
{
  document.addEventListener('com:change', function () {
    MoveTest.updateType()
  })

  let _events = [
    'css',
    'js',
  ]
  _events.forEach(_event => {
    document.addEventListener('change:' + _event, function (e) {
      if (window.vvg.page[_event]!= e.detail) {
        window.vvg.page[_event]= e.detail
        MoveTest.updateType()
      }
    })
  })

  let eventListeners = {}
  window.vvg.updateEventListen = function (name, val = window.vvg.page.ext) {
    let eventName = 'change:' + name
    eventListeners[eventName] = function (e) {
      if (val[name]!= e.detail) {
        val[name]= e.detail.trim()
        window.MoveTest.updateType()
      }
    }
    document.removeEventListener(eventName, eventListeners[eventName])
    document.addEventListener(eventName, eventListeners[eventName])
  }
}

window.MoveTest = MoveTest

import './codemodal'
